package com.zwz.crm.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * Created by zhaowuz on 2020/1/12.
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginInterceptor.class);

    String isLogin;

    public LoginInterceptor() {
    }

    public LoginInterceptor(String isLogin) {
        this.isLogin = isLogin;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String url = request.getRequestURI();
        LOGGER.info("Interceptor URL =  {} ", url);
        // 已登录
        if (!Objects.isNull(request.getSession().getAttribute("isLogin")) && isLogin.equals(request.getSession().getAttribute("isLogin"))) {
            return true;
        }
        request.setAttribute("msg", "无权限请先登录");
        // 获取request返回页面到登录页
        request.getRequestDispatcher("/loginOut").forward(request,response);
        return false;
    }
}
